//
//  DDIDCardInputUndoButton.m
//  GSDache
//
//  Created by guoshikeji_a on 2018/2/6.
//  Copyright © 2018年 tanyin. All rights reserved.
//

#import "DDCustomNumberInputtUndoButton.h"

@interface DDCustomNumberInputtUndoButton () {
    
}

/**
 长按时一直删除
 */
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesure;

/**
 *target
 */
@property (nonatomic, weak) id target;

/**
 *longSelector
 */
@property (nonatomic, assign) SEL longSelector;


#pragma mark - property

/**
 *是否长按中 //default false
 */
@property (nonatomic, assign) BOOL isLongPress;

/**
 *长按时触发的时间
 */
@property (nonatomic, strong) NSDate *longPressFireDate;

@end

@implementation DDCustomNumberInputtUndoButton

- (UILongPressGestureRecognizer *)longPressGesure {
    if (!_longPressGesure) {
        _longPressGesure = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesureAction:)];
    }
    return _longPressGesure;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        if (![self.gestureRecognizers containsObject:self.longPressGesure]) {
            [self addGestureRecognizer:self.longPressGesure];
        }
        _isLongPress = false;
    }
    return self;
}

- (void)addLongPressUndoTarget:(id)target action:(SEL)action {
    self.target = target;
    self.longSelector = action;
}

- (void)setIsLongPress:(BOOL)isLongPress {
    _isLongPress = isLongPress;
    if (_isLongPress) {
        
    }else {
        if (self.longPressFireDate) {
            self.longPressFireDate = nil;
        }
    }
}

#pragma mark - longPressGesureAction
- (void)longPressGesureAction:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            {//开始
                self.isLongPress = true;
                [self startUndoAction];
            }
            break;
        case UIGestureRecognizerStateChanged: {
            
        }
            break;
        default:
        {//结束
            self.isLongPress = false;
        }
            break;
    }
}

- (void)startUndoAction {
    if (!_isLongPress) {
        return;
    }
    if (self.target && [self.target respondsToSelector:self.longSelector]) {
        /**
         执行方法
         */
        id target = _target;
        SEL selector = _longSelector;
        ((void (*)(id, SEL))[target methodForSelector:selector])(target, selector);
        /**
         延时下一次
         */
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self startUndoAction];
//        });
        [self performSelector:@selector(startUndoAction) withObject:nil afterDelay:0.1];
    }
}

@end
